package com.thunder.kocho.loki;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.graphics.Rect;
import android.view.animation.LinearInterpolator;
import com.thunder.kocho.loki.builder.KeyFrameAnimatorBuilder;
import com.thunder.kocho.loki.shape.DropLoki;
import java.util.ArrayList;

/**
 * @author Hilex
 * @date 2021-3-21
 */
public class FanDrop extends LokiGroup {

    @Override
    protected ArrayList<Loki> onCreateChild() {
        ArrayList<Loki> lokis=new ArrayList<>();
        for(int i=0;i<4;i++){
            Loki loki=new FanDropLoki(i);
            loki.setAnimationDelays(0);
            lokis.add(loki);
        }
        return lokis;
    }

    @Override
    protected void onBoundsChange(Rect bounds) {
        super.onBoundsChange(bounds);
        bounds=clipSquare(bounds);
        float length=bounds.width()/2f;
        int cx=bounds.centerX();
        int cy=bounds.centerY();
        for(Loki loki:mLokis){
            loki.setLokiBounds((int)(cx-length/2f),bounds.top,(int)(cx+length/2f),cy);
            loki.setPivotX(cx);
            loki.setPivotY(cy);
            if(loki instanceof DropLoki){
                ((DropLoki) loki).setLeft(cx-length/2f);
                ((DropLoki) loki).setTop(bounds.top);
                ((DropLoki) loki).setLength(length);
            }
        }
    }

    @Override
    protected void onChildCreated(ArrayList<Loki> lokis) {

    }

    private static class FanDropLoki extends DropLoki{

        private final int index;

        public FanDropLoki(int index){
            this.index=index;
        }

        @Override
        protected Animator onCreateAnimator() {
            return new KeyFrameAnimatorBuilder()
                    .rotate(new float[]{0f,0.05f,0.2f,0.25f,0.3f,0.45f,0.5f,0.55f,0.7f,0.75f,0.8f,0.95f,1f},0,0,45+index*90,45+index*90,45+index*90,0,0,0,-45-index*90,-45-index*90,-45-index*90,0,0)
                    .scale(new float[]{0f,0.05f,0.2f,0.25f,0.3f,0.45f,0.5f,0.55f,0.7f,0.75f,0.8f,0.95f,1f},0f,0f,1f,1f,1f,0f,0f,0f,1f,1f,1f,0f,0f)
                    .interpolator(new LinearInterpolator())
                    .duration(4000)
                    .count(ValueAnimator.INFINITE)
                    .target(this)
                    .build();

        }
    }
}
